package com.ias.agdis_r.activity.task;

import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseActivity;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.adapter.MemberAdapter;
import com.ias.agdis_r.bean.user.User;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.manager.MessageManager;
import com.ias.agdis_r.manager.ServiceManage;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.request.ForwardTaskRequest;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.request.GetGroupmemberRequest;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.request.GetHandOverUserRequest;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.request.TransferTaskRequest;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.response.ForwardTaskResponse;
import com.ias.agdis_r.terminalmanager.restful.task.vo.ForwardTaskRequestVO;
import com.ias.agdis_r.terminalmanager.restful.task.vo.TransferTaskRequestVO;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.network.HttpUtil;
import com.ias.agdis_r.view.MyProgressBar;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import me.maxwin.view.XListView;

/**
 * 获取同组人员界面
 * Created by guoxr on 2015/12/4.
 */
public class TaskSendOtherActivity extends BaseActivity implements XListView.IXListViewListener{
    private ActionBar actionBar;
    private XListView listView;
    private List<User> memberlist = new ArrayList<User>();
    private TextView selectCount;
    private MyProgressBar progressBar;
    private Button btnSend;
    private MemberAdapter adapter;
    private boolean isRefresh = false;
    public final static int TYPE_SENDTO = 0;
    public final static int TYPE_TRANSFER = 1;
    private int type = 0;
    private String tnb = "";
    private String [] tnbs = null;
    private TimeoutTimerTask timeoutTimerTask;
    private Timer timeoutTimer;
    private Handler myhandler = new Handler();
    private TextView noPerson;
    /**
     * 停止刷新任务
     */
    class TimeoutTimerTask extends TimerTask {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, getString(R.string.request_err_timeout), false);

            myhandler.post(new Runnable() {
                @Override
                public void run() {
                    stopRefresh();
                }
            });
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_sendother);
            noPerson = (TextView) findViewById(R.id.no_person);
            Intent intent = getIntent();
            //读取TNB及，当前的类型
            type = intent.getIntExtra("type", this.TYPE_SENDTO);
            if(type == 0){
                tnb = intent.getStringArrayExtra("tnb")[0];
            }else if(type == 1){
                tnbs = intent.getStringArrayExtra("tnb");
            }

            actionBar = getActionBar();
            initActionBar();
            btnSend = (Button) findViewById(R.id.sendother_confirm);
            btnSend.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    String stenList = "";
                    List<String> tenList = adapter.getMultiselectList();
                    if(tenList.size()==0){
                        if (type == TYPE_SENDTO) {
                            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, getString(R.string.choosePerson), false);
                        } else if (type == TYPE_TRANSFER) {
                            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, getString(R.string.choosePerson), false);
                        }
                        return;
                    }
                    else{
                        for(String ten:tenList){
                            stenList = stenList +  ten +"|";
                        }
                        stenList = stenList.substring(0, stenList.length()-1);
//                        executeTTAS(tnb, stenList);
                    }
                    if (type == TYPE_SENDTO) {
                        executeTTAS(tnb, stenList);
                    } else if (type == TYPE_TRANSFER) {
                        executeTTAL(tnbs,stenList);
                    }
                }
            });
            progressBar = (MyProgressBar) findViewById(R.id.progressBar);
            progressBar.setOnVisibilityChangeListener(new MyProgressBar.OnVisibilityChangeListener() {
                @Override
                public void onVisibilityChanged(boolean visibity) {
                    if (visibity) {
                        btnSend.setVisibility(View.GONE);
                    } else {
                        btnSend.setVisibility(View.VISIBLE);
                    }
                }
            });

            if(type==TYPE_SENDTO){
                btnSend.setText(getString(R.string.sendto));
            }else if(type==TYPE_TRANSFER) {
                btnSend.setText(getString(R.string.transfer));
            }
            serListAdapter();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    private void serListAdapter() {
        selectCount = (TextView) findViewById(R.id.sendother_num);
        listView = (XListView) findViewById(R.id.ListView);
        adapter = new MemberAdapter(this,memberlist,type);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {
                if (position > 0) {
                    adapter.selectItem(position - 1);
                    updateSeletedCount();
                }

            }
        });
        listView.setXListViewListener(TaskSendOtherActivity.this);
        listView.setPullLoadEnable(false);
        listView.setRefreshTime(S.getNowTime4());
        listView.startRefreshView();
        onRefresh();
    }

    private void updateSeletedCount() {
        if(type==TYPE_SENDTO){
            if (null != selectCount) {
                selectCount.setText(getString(R.string.TSO_1) + adapter.getMultiselectList().size() + getString(R.string.TSO_2));
            }
        }
    }

    private void initActionBar() {
        actionBar.setCustomView(LayoutInflater.from(TaskSendOtherActivity.this)
                .inflate(R.layout.actionbar_back_and_home, null));
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        TextView title = (TextView) findViewById(R.id.txt_title);
        title.setText(R.string.choosePerson2);
        ImageView back = (ImageView) findViewById(R.id.action_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        ImageView home = (ImageView) findViewById(R.id.action_home);
        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TaskSendOtherActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void operateResponseSucess(String serviceId, BaseResponse response) {
        if (MessageModel.TTAS.equals(serviceId)){
            ForwardTaskResponse forwardTaskResponse = (ForwardTaskResponse) response;
            String tnb = forwardTaskResponse.getTnb();
            receiveTTAS(tnb);
        }else if (MessageModel.TTAL.equals(serviceId)){
            finish();
        }
    }

    @Override
    protected void updateUI(String tag) {
        if(tag.equals(MessageModel.QQRY) || tag.equals(MessageModel.GHOU)) {
            //接收QQRY,GHOU响应处理
            receiveQQRY();
        }
    }

    @Override
    protected void updateUI(String tag,String tnb) {

    }

    /**
     * 发送TTAS消息
     */
    private void executeTTAS(String tnb,String stenList){
        if(S.isNotEmpty(tnb)&&S.isNotEmpty(stenList)){
            HttpUtil.getInstance().sendRequest(initTTAS(tnb, stenList), MessageModel.TTAS, true);
        }
    }

    private ForwardTaskRequest initTTAS(String tnb,String stenList){
        ForwardTaskRequest forwardTaskRequest = new ForwardTaskRequest();
        ForwardTaskRequestVO forwardTaskRequestVO = new ForwardTaskRequestVO();
        forwardTaskRequestVO.setTnb(tnb);
        forwardTaskRequestVO.setTenb(stenList);
        forwardTaskRequest.setForwardTaskRequestVO(forwardTaskRequestVO);
        return forwardTaskRequest;
    }

    /**
     * 发送TTAL消息
     */
    private void executeTTAL(String[] mtnb,String ten) {
        StringBuffer sbTnb = new StringBuffer();
        for (int i = 0; i < mtnb.length; i++) {
            sbTnb.append(mtnb[i] + "|");
        }
        sbTnb.substring(0,sbTnb.length()-1);
        HttpUtil.getInstance().sendRequest(initTTAL(sbTnb.toString(), ten), MessageModel.TTAL, true);
    }

    private TransferTaskRequest initTTAL(String tnb,String ten){
        TransferTaskRequest transferTaskRequest = new TransferTaskRequest();
        TransferTaskRequestVO transferTaskRequestVO = new TransferTaskRequestVO();
        transferTaskRequestVO.setTnb(tnb);
        transferTaskRequestVO.setTenb(ten);
        transferTaskRequest.setTransferTaskRequestVO(transferTaskRequestVO);
        return transferTaskRequest;
    }

    /**
     * 发送获取可转发/移交人员消息
     */
    private void executeQQRY(){
        if(!isRefresh) {
            this.isRefresh = true;
            startTimeoutTimer();
            if(type == TYPE_SENDTO) {
                HttpUtil.getInstance().sendRequest(initQQRY(), MessageModel.QQRY, false);
            }else if (type == TYPE_TRANSFER){
                HttpUtil.getInstance().sendRequest(initGHOU(), MessageModel.GHOU, false);
            }
        }
    }

    private GetGroupmemberRequest initQQRY() {
        GetGroupmemberRequest getGroupmemberRequest = new GetGroupmemberRequest();
        getGroupmemberRequest.setOnl("Y");
        return getGroupmemberRequest;
    }

    private GetHandOverUserRequest initGHOU() {
        GetHandOverUserRequest getHandOverUserRequest = new GetHandOverUserRequest();
        getHandOverUserRequest.setOnl("Y");
        return getHandOverUserRequest;
    }
    /**
     * 接收TTAS消息
     */
    private void receiveTTAS(String tnb){
        if (this.tnb.equals(tnb)) {
            finish();
        }
    }

    private void stopRefresh(){
        //停止刷新
        String str = S.getNowTime4();
        listView.stopRefresh();
        listView.setRefreshTime(str);
        this.isRefresh = false;
    }
    /**
     * 接收QQRY消息
     */
    private void receiveQQRY(){

        User[] userList = DataManager.getInstance().getMemberList();
        if(userList!=null)
        {
            memberlist.clear();
            for(User user:userList){

                if(type==this.TYPE_TRANSFER)
                {
                    String memberenb = user.getEnb();
                    String memberrli = user.getRli();
                    String myenb = JavaBeanManager.getInstance().getUserinfo().getEnb();
                    String myrli = JavaBeanManager.getInstance().getUserinfo().getRli();
                    //如果组员是自己，不显示
                    if(memberenb.equals(myenb)){
                        continue;
                        //如果角色与自己不同，不显示
                    }
                }
                memberlist.add(user);
            }
        }

        if(adapter!=null){
            //更新adapter
            adapter.setList(memberlist);
            if (noPerson != null){
                if (memberlist.size() == 0){
                    noPerson.setVisibility(View.VISIBLE);
                } else {
                    noPerson.setVisibility(View.GONE);
                }
            }
            adapter.notifyDataSetChanged();
        }
        EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, getString(R.string.refresh_member_succes), false);
        stopTimeoutTimer();
        stopRefresh();
    }


    @Override
    public void onRefresh() {
        //需要对服务器应答超时进行处理
        executeQQRY();
    }

    @Override
    public void onLoadMore() {

    }

    /**
     * 开始刷新任务
     */
    public void startTimeoutTimer(){
        if(timeoutTimer==null) {
            timeoutTimer = new Timer();
        }
        if(timeoutTimerTask!=null){
            timeoutTimerTask.cancel();
            timeoutTimerTask = null;
        }

        timeoutTimerTask = new TimeoutTimerTask();
        // 新建一个任务
        timeoutTimer.schedule(timeoutTimerTask, 12 * 1000);
    }

    /**
     * 停止显示进度条任务
     */
    public void stopTimeoutTimer()
    {
        if (timeoutTimer != null){
            if (timeoutTimerTask != null){

                timeoutTimerTask.cancel();  //将原任务从队列中移除
                timeoutTimerTask = null;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimeoutTimer();
    }
}
